package com.enjoy.prepare.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 类说明：演示反射的使用
 */
public class ReflectDemo {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {

        //实例化对象的标准用法，也就所谓的正
        Servant servant = new Servant();
        servant.service("Hello");

        //通过全限定名拿到类的class对象
        Class<?> servantClazz = Class.forName("com.enjoy.prepare.reflect.Servant");

        //通过class对象拿到类的实例
        Servant servantInstance = (Servant) servantClazz.newInstance();
        servantInstance.service("Hello");

        //通过class对象拿到方法列表
        Method[] methods = servantClazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("方法的名称:" + method.getName());//打印方法名称
            if ("service".equals(method.getName())) {
                try {
                    method.invoke(servantClazz.newInstance(), "fuck");
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
